#include "comm.hpp"
#include <iostream>
#include <unistd.h>
class Init
{
public:
    Init()
    {
        // 1.获取kye
        key_t key = GetKey();
        std::cout << "获取key:" << toHex(key) << std::endl;
        // 2.创建物理内存
        _shmid = CreateShm(key);
        std::cout << "创建物理内存,shmid:" << _shmid << std::endl;
        // 3.挂载
        _s = (char *)shmat(_shmid, nullptr, 0);
        if (_s == nullptr)
            exit(1);
        std::cout << "挂载成功,起始地址:" << _s << std::endl;
        // 4.打开管道
        makefifo();
        _fd = open(filename.c_str(), O_RDONLY, 0664);
    }
    ~Init()
    {
        // 取消关联
        shmdt(_s);
        std::cout << "取消挂载" << std::endl;
        // 删除物理空间
        shmctl(_shmid, IPC_RMID, nullptr);
        std::cout << "从OS中移除" << std::endl;
        close(_fd);
        unlink(filename.c_str());
    }

public:
    int _shmid;
    char *_s;
    int _fd;
};

int main()
{
    Init init;
    // 可以直接进程通信了!!!
    while (true)
    {
        int code = 0;
        int n = read(init._fd, &code, sizeof(int));
        if (n > 0)
        {
            std::cout << "共享内存的内容:" << init._s << std::endl;
            sleep(3);
        }
        else  if(n==0)
        {
            std::cout << "写端关闭,me too!" << std::endl;
            break;
        }
    }
    return 0;
}